import moment from "moment";

/**
 * 根据文件类型前端导出下载文件
 * @param type     文件类型：String 
 *   包括downloadUrl(后端链接直接点击可下载)，fileBlob(文件流blob对象), 
 *       base64Str(base64字符串), previewUrl(可预览文件，希望做成阻止预览，直接下载的效果)
 * @param file     文件 String or Object
 * @param fileName 文件名 String
 * @returns：undefined
 * @actions : downloadFile('downloadUrl','https://ihruat.gemdale.com/sign/埋点统计.xls','downloadUrl文件下载')
 *            
 *            downloadFile('fileBlob',{size: 5632, type: 'application/binary'},'blob文件下载')
 * 
              downloadFile('base64Str',
              { fileStr:'iVBORw0KGgoAAAANSUhEUgAAACEAAAAhCAYAAABX5MJvAAAACXBIWXMAAAsSAAALEgHS3X78AAAEk0lEQVRYhbVXS09bRxQ+N3bNRdjEai3UYiGMYdFFUKzykKoKSpWN1QU1YtVVCavu4vML4vQPDFGURRYosIGtQxeVF8hG2cGiICMUVUh1awlSQaldVLBsB1fncsaM773Dq80nWXPndeabOd85MzYajQbcBogYBIAYAGwKIUq3MsK442i5BhBxDgD+AoAslVy/NW58Eog4AwAvHR0AD4UQC47Wa+A2J5HgcgsA+rgkzDhGvkcSQeWbtLDpGHFDeHXDWXi06wiLL81dVH4JAPcBoAAAd7k9p8yd4XnUn75KuK6aYAI5XkhiSwgR437y/XdK3yshREI3DwAmLiOic8ecYmiNy/uImKQPIQTt9AW3vyAC/D3jNo/taaEjEZGHIoSYoJ1yPaGMeWsr1f5XPA9t9lyh1YTcGSKS8B5wvQAXPo+xMGNcT3M/6eUBIk5cN2J0JBYU8WWV9k8RkRbqVdq+4R8d+R63+W3zLnWHqzB5t+T/FKv/TwD4SOn+jQ1v8okkmLSEHF8mG0KI65FARGnMEVas+t8BIAAAiyxMB+lwOCympqagv79fJZtExJwS7mS7JbdYJFxCrsxhtQkXd8UjGYqOrZwjUq1Wf/H5fB/YO1ZWVirZbNZUmlo24imXyyQgoTCnXdOEzzOZzJtMJkPsvweAjwHg23g8/ta+CGPO4/F85mglAfX2eldXV1X7sUwmsxWPx98AhyiRAE4q5JKHPFeKMitj336MNsRkdWNjA5aXl5u9pmnC+Pj4cx4j75rm+DscZsD+iiik6pxw1vhbakOHZpZcWlqC9fV1KBQKFdl2cHAQ54UdOcPL8S2j4Gel77kQIsmL51j9CQ5fiQm7QRV+v/8PGc5dXV39tVrNCtu9vb2/T05Omna8QogCJ5a0Ev9PJQGGzBspRCR1R2zjr0Qi0aLnTk5kKXkS0teOY+KwDXI+KNKiHR0drxuNRq9hGIGrFq7X6z5H4wUeczpYcM2Y7Pu0LQERDoeHh+8ZhtFs2NnZqRaLRdfFstnsJ6FQqNLW1nZgGMaZaZrekZGRsDIkpSVBCUYhUFbeDD8NDQ19AQBRqmxvb8P8/LwrAQKJk8O9R7bt7+9XJicnZc6w3KkjIQW3yIReA8A98mVPT8+PnLhgYGAABgcH4fT0tGXy7u6uVYbDYWhvb2/pGxsbO2FicoNaEhJSE++4XmI3WSQo/mdnZx2TEM9v8Onp6WpfX5/9pD5Uvq3Xmu49IZ9qFPu/KjmAoiRXq9WWHTNccHZ2pnUVJy0rAl1PQgiRYnE+UpqfCCFyiEhR9DW5YXR01DpuwzDq0WjU1ZZtUZkYc3wLl7QkmAjdfimXf1nE/m4+n4d8Pr/IFx/lG4eNzs7OoiLKpPoYVqElwURKLhNlzn/CJ0ax/rhardZ9Pp9ljwR5dHQEgUDA7zDqgktJaCCfcEkmYPn18PCw1N3dHYJzYZ4eHx//Y5pmSDFRcDenF+ZlmFNyx0uZQyqVyjM5x+PxtAeDQZXA2v9Kgq9z+QJf4/KraDT6A905jgnngtQ9hCxo35j/AfKZSLDuhqtsvQ8SNwMA/AsjMqbmUsz4jAAAAABJRU5ErkJggg==',
                fileType:'image/png'
              }, 'base64Str下载')

              downloadFile('previewUrl',
              { fileUrl:'http://pswebback.shjec.cn:4434/pictures/uat/empInfo/zhanghf_PDF/100026.pdf',
                fileType:'application/pdf'
              }, 'previewUrl下载')
 */
//base64Str转blob对象
export function base64StrToBlob(base64Str, mimeTypeStr) {
  var bstr = window.atob(base64Str), n = bstr.length, u8arr = new Uint8Array(n);
  console.log('bstr',bstr);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mimeTypeStr });
}
 //根据blob对象进行IE浏览器与非IE浏览器的下载处理
export function downloadBlobFile(fileBlob, fileName){
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(fileBlob, fileName); // 兼容IE10
  } else {
    let aElement = document.createElement('a'); //创建元素
    document.body.appendChild(aElement);
    aElement.style.display = 'none';
    // aElement.href = window.URL.createObjectURL(fileBlob);
    return window.location.href = window.URL.createObjectURL(fileBlob)
    aElement.download = fileName;
    aElement.click();
    document.body.removeChild(aElement);
  }
}
export function downloadFile(type, file, fileName) {
// 1.没传type或type类型不符合条件，不做任何处理、
  const typeArr = ['downloadUrl','fileBlob','base64Str','previewUrl']
  if(!type || !typeArr.includes(type)) return 
// 2.type为downloadUrl代表可直接打开的链接
  if(type === 'downloadUrl' && file){
    window.open(file); return
  }
// 3.type为base64Str与previewUrl均转为blob对象
  let fileBlob
  switch(type){
    case 'fileBlob':
      fileBlob = file;
      downloadBlobFile(fileBlob,fileName); break;
    case 'base64Str':
      fileBlob = base64StrToBlob(file.fileStr, file.fileType); 
      downloadBlobFile(fileBlob,fileName); break;
    case 'previewUrl':
    // fileUrl与当前浏览器url必须一致，也就是同源，否则会报跨域错误
      const oReq = new XMLHttpRequest();
      oReq.open("GET", file.fileUrl, true);
      oReq.responseType = "blob";
      oReq.onload = function() {
        fileBlob = new Blob([oReq.response], {type: 'application/pdf'}); 
        // fileBlob = new Blob([oReq.response], {type: file.fileType}); //'application/pdf'
        console.log(fileBlob, 'bbb');
        downloadBlobFile(fileBlob,fileName);
      };
      oReq.send(); break;
  }
}

/**
 * @param {*} val1 当前日期控件值
 * @param {*} val2 对应日期控件值
 * @param {*} isStartDate  是否是开始日期
 * @param {*} isDisabledSameDate  开始日期与结束日期是否可为同一天，默认可以
 */
export function disabledDate(val1, val2, isStartDate, isDisabledSameDate = false ) {
  //当日期控件弹出时，val1为moment对象，此时val2有值时走禁用逻辑   
  // console.log(val1,val2,moment(val1).format('YYYY-MM-DD'),moment(val2).format('YYYY-MM-DD')  );
  if(!val1 || !val2) return false
  const disabledSameDate = isStartDate ? 
    moment(val2).format('YYYY-MM-DD') <= moment(val1).format('YYYY-MM-DD') : 
    moment(val1).format('YYYY-MM-DD') <= moment(val2).format('YYYY-MM-DD')
  const disabledDifDate = isStartDate ? 
    moment(val2).format('YYYY-MM-DD') < moment(val1).format('YYYY-MM-DD') : 
    moment(val1).format('YYYY-MM-DD') < moment(val2).format('YYYY-MM-DD')
  return isDisabledSameDate ? disabledSameDate : disabledDifDate
}

























/**
 * 
 * @params: 
 *    [ {id: 1, name: '部门1', pid: 0},
        {id: 2, name: '部门2', pid: 1},
        {id: 3, name: '部门3', pid: 1},
        {id: 4, name: '部门4', pid: 3},
        {id: 5, name: '部门5', pid: 4} 
      ]
 * @returns：
      [ { id: 1, name: '部门1', pid: 0, 
          children: 
            [{id: 2, name: '部门2', pid: 1, children:[]},
             {id: 3, name: '部门3', pid: 1, children:[]}
            ]
      } ]
 */
      export function arrayToTree(items) { 
        const getChildren = (data, result, pid) => {
          for (const item of data) {
            if (item.pid === pid) {
              const newItem = {...item, children: []};
              result.push(newItem);
              getChildren(data, newItem.children, item.id);
            }
          }
        }
        const arrayToTree = (data, pid) => {
          const result = [];
          getChildren(data, result, pid)
          return result;
        }
        getChildren(data, [], pid)
      }
      